package com.yinsin.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;

public class ObjectUtils {

    /**
     * 指定输出流输出对象
     * 
     * @param optstream
     * @param obj
     * @throws IOException
     */
    public static void transfer(final OutputStream optstream, final Object obj) throws IOException {
        ObjectOutputStream oout = new ObjectOutputStream(optstream);
        oout.writeObject(obj);
        oout.flush();
        oout.close();
    }

    /**
     * 将对象写入到文件（对象序列化）
     * 
     * @param t
     *            对象
     * @param filePath
     *            保存到文件的路径
     * @return 文件路径
     * @throws IOException
     */
    public static <T> String objectToFile(final T t, final String filePath) throws IOException {
        FileOutputStream out = new FileOutputStream(new File(filePath));
        transfer(out, t);
        return filePath;
    }

    /**
     * 将对象序列化文件还原为对应的对象实体
     * 
     * @param t
     *            对象类型
     * @param filPath
     *            序列化文件路径
     * @return 对象实体
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    public static <T> T fileToObject(T t, String filPath) throws FileNotFoundException, IOException, ClassNotFoundException {
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream(filPath));
        t = (T) oin.readObject();
        oin.close();
        return t;
    }
    
    /**
     * 获取jar包的所在目录
     * @param url
     * @return
     */
    public static String getJarDir(String url) {
        if (url != null && url.startsWith("file")) {
            url = url.substring(6);
            url = url.substring(0, url.indexOf("!"));
            File jar = new File(url);
            url = jar.getParentFile().getPath();
        } else {
            url = url.substring(0, url.lastIndexOf("/"));
        }
        return url;
    }
    
    /**
     * 获取jar包的所在目录，或者class文件所在目录
     * @return
     */
    public static String getBaseDir(String fileName){
        String path = null;
        URL url = ObjectUtils.class.getResource(null == fileName ? "/log4j.properties" : fileName);
        if(null != url){
            path = url.getPath();
            path = CommonUtils.stringUncode(path);
            path = getJarDir(path);
            if(path.startsWith("/") && path.indexOf(":") != -1){
                path = path.substring(1);
            }
            path = path.replaceAll("\\\\", "/");
        }
        return path;
    }

}
